<template>
  <div id="warehouse" class="heightAll widthAll home"> <!--这样可以设置多个class-->
    <top tar="warehouse"/>
    <!--表格组件， 定义data后，prop即属性-->
    <div class="widthAll" style="margin-bottom: 20px;"> <!--搜索栏-->
      <!--input组件,有两个是js定义输入限制， clearable可清空-->
      <el-input v-model="form.name" class="search-content" clearable
                maxlength="15"
                placeholder="输入产品名称"
                prefix-icon="el-icon-search"
                show-word-limit
                style="width: 200px; margin-right: 10px;"
                type="text">
      </el-input>
      <el-select v-model="form.category" clearable placeholder="请选择产品分类" style="margin-right: 15px;">

        <el-option
            v-for="category in categories"
            :key="category.id"
            :label="category.name"
            :value="category.id">
        </el-option>
      </el-select>
      <!--button组件-->
      <el-button icon="el-icon-search" type="primary" @click="search">搜索</el-button>
      <el-button icon="el-icon-back" type="primary" @click="returnHome">返回</el-button>
    </div>


    <el-table v-loading="loading" :data="products" border class="el-table" header-align="center"
              highlight-current-row stripe style="width: 100%; text-align: center;">
      <ex-table-column :autoFit='true' label="产品编号" prop="pid" width="320px">
        <template slot-scope="scope">
          <el-tag style="text-align: center;" type="success"><span>{{ scope.row.pid }}</span>
          </el-tag>
        </template>
      </ex-table-column>
      <ex-table-column :autoFit='true' label="产品名称" prop="pname">
      </ex-table-column>
      <ex-table-column :autoFit='true' label="产品分类" prop="category" width="130px">
        <template slot-scope="scope">
          {{ categoryMap.get(scope.row.category) }}
        </template>
      </ex-table-column>
      <ex-table-column :autoFit='true' label="产品库存" prop="number">
      </ex-table-column>
      <ex-table-column :autoFit='true' label="操作">
        <template slot-scope="scope">
          <el-link icon="el-icon-edit" type="primary" @click="updateInfo(scope.$index,scope.row)">修改信息
          </el-link>
        </template>
      </ex-table-column>
    </el-table>
    <br>
    <el-pagination :current-page="form.pageNo"
                   :page-size="form.pageSize"
                   :page-sizes="[5,10,15]"
                   :total="total"
                   background
                   class="my-changePage"
                   layout="total, sizes, prev, pager, next, jumper"
                   @current-change="change"
                   @size-change="handleSizeChange">
    </el-pagination>


    <el-dialog :visible.sync="visible" style="font-family: 'Microsoft YaHei UI',sans-serif"
               width="40%">
      <div slot="title" class="my-dialog-title">
        <i class="el-icon-s-tools"></i>修改产品信息
      </div>
      <!--最tmd蛋疼的地方，model，ref 得同名，prop和对象也要一样，才能正确重置      -->
      <el-form ref="product" :model="product" :rules="rules" label-position="left" label-width="80px" status-icon>
        <el-form-item label="产品名称" prop="pname">
          <el-input v-model="product.pname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="产品分类" prop="category">
          <el-select v-model="product.category" clearable
                     placeholder="请选择产品分类">
            <el-option
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :value="category.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm">取 消</el-button>
        <el-button type="primary" @click="submit">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import top from "../../components/backToTop";
import {getCategories} from "../../api/category";
import {getProducts, modifyProductInfo} from "@/api/product";

export default {
  name: "index",
  components: {
    top
  },
  data() {
    return {
      products: [{pid: 0, pname: 'product', category: 0, number: 0}],
      categories: [{id: 0, name: 'category'}],
      categoryMap: new Map(),
      productIndex: 0,
      form: {
        pageNo: 1,
        pageSize: 5,
        category: null,
        name: null
      },
      total: 0,
      loading: true,
      visible: false,
      product: {pid: 1, pname: '', category: 1, number: 0},
      rules: {
        pname: [
          {required: true, message: '请输入产品名称', trigger: 'blur'},
          {pattern: /^[a-zA-Z0-9\u4e00-\u9fa5]+$/, message: "请勿输入特殊字符", trigger: "blur"},
          {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
        ],
        category: [
          {required: true, message: '请选择产品分类', trigger: 'change'}
        ],
      },

    }
  }, methods: {
    change(currentPage) {
      this.form.pageNo = currentPage;
      this.getProducts();
    },
    handleSizeChange(size) {
      this.form.pageSize = size;
      this.getProducts();
    },
    getProducts() {
      const _this = this;
      getProducts(_this.form).then(resp => {
        _this.products = resp.message.records;
        _this.loading = false;
        //当我在搜索栏写内容时，这时不点搜索，而点击第二页，这时会传正确参数。但由于结果根本没有第二页，所以强制变成了1 ，此时 pageNo = 2，
        //之后，我删掉搜索栏后，点击搜索，此时pageNo=2传过去只能接收到第二页的内容，所以下面的代码解决这个bug
        _this.form.pageNo = resp.message.current;
        _this.total = resp.message.total;
      })
    },
    getCategories() {
      const _this = this;
      getCategories().then(resp => {
        _this.categories = resp.message;
        _this.categories.forEach(item => {
          _this.categoryMap.set(item.id, item.name);
          _this.categoryMap = new Map(_this.categoryMap);
        })
      })
    },
    updateInfo(index, row) {
      if (this.$refs.product)
        this.$refs.product.resetFields();
      this.visible = true;
      //直接=row，是引用复制，会牵扯到本体
      this.productIndex = index;
      this.product = JSON.parse(JSON.stringify(row));
    },
    resetForm() {
      this.visible = false;
    }, submit() {
      const _this = this;
      _this.$refs.product.validate((valid) => {
        if (valid) {
          modifyProductInfo(_this.product).then(resp => {
            if (resp.code === 200) {
              _this.$message.success("更新成功");
              _this.visible = false;
              //不必重新获取，在本地更新即可
              let obj = JSON.parse(JSON.stringify(_this.product));
              //_this.products[_this.productIndex] = obj  没必要，下面的代码做了
              //更新视图, model,index,row
              _this.$set(_this.products, _this.productIndex, obj)
            } else {
              _this.$message.warning(resp.message);
            }
          })
        }
      })
    }, search() {
      this.getProducts();
    }, returnHome() {
      window.location.reload();
    }
  }, mounted() {
    this.getProducts();
    this.getCategories();
  }
}
</script>

<style scoped>

</style>